import {
  addDriveParaLib,
  delDriveParaLib,
  delDriveParasLib,
  driveParaLibExcelExport,
  getDriveParaLibByPage,
  updateDriveParaLib,
  uploadDriveParaLibExcel,
  addDriveParaLibs,
} from '@/services/drivepara/driveparalib';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper, ProCard, ProColumns } from '@ant-design/pro-components';
import ProList from '@ant-design/pro-list';
import { Button, Space, Tag, message } from 'antd';
import { ReactText, useEffect, useRef, useState } from 'react';
import DriveParaLibCommon from './driveParaLibCommon';
import UploadFile from '@/components/UploadExcel';
import UploadFileSave from '@/components/UploadExcelSave';
import Tree, { DataNode } from 'antd/lib/tree';
import DriveParaLibSubtitle from '@/components/DriveParaCalc/DriveParaLibSubtitle';
import DriveParaLibDescription from '@/components/DriveParaCalc/DriveParaLibDescription';
import DriveParaDescription from '@/components/DriveParaCalc/DriveParaDescription';
import DriveParaCommon from '@/components/DriveParaCalc/DriveParaCommon';
import DriveParaSubtitle from '@/components/DriveParaCalc/DriveParaSubtitle';
// import type { UploadFile, UploadProps } from 'antd/es/upload/interface';

const DriveParaLib: React.FC<{}> = () => {
  const [expandedRowKeys, setExpandedRowKeys] = useState<readonly ReactText[]>([]);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [libCommVis, setLibCommVis] = useState(false);
  const [values, setValues] = useState({});
  const [axiosCreate, setAxiosCreate] = useState<Boolean>(false);
  const driveRef = useRef(null);
  const uploadRef = useRef(null);
  const [uploadVis, setUploadVis] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<ReactText[]>([]);
  const formData = new FormData();
  // const [fileList, setFileList] = useState<UploadFile[]>([]);
  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: ReactText[]) => setSelectedRowKeys(keys),
  };
  const actionRef = useRef<ActionType>();

  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>(['lib3']);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([
    'lib4-0',
    'lib4-1',
    'lib4-2',
    'lib4-3',
    'lib4-4',
  ]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);

  const [kpDefaultChecked, setKpDefaultChecked] = useState(false);

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 40,
      align: 'center',
    },
    {
      title: '轴名称',
      search: false,
      dataIndex: 'shaftName',
      width: 60,
      align: 'center',
    },
    {
      title: '驱动类型',
      width: 60,
      search: false,
      align: 'center',
      key: 'driveType',
      dataIndex: 'driveType',
      valueType: 'select',
      valueEnum: {
        1: { text: 'V90', status: 'Default' },
        2: {
          text: 'S210',
          status: 'success',
        },
      },
    },
    {
      title: '电机订货号',
      search: false,
      align: 'center',
      dataIndex: 'motorOrderNum',
      width: 100,
    },
    // {
    //   title: '电机ID',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'motorId',
    //   width: 60,
    // },
    // {
    //   title: '编码器',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'ecoderType',
    //   valueType: 'select',
    //   valueEnum: {
    //     0: { text: '单圈绝对值编码器' },
    //     1: { text: '多圈绝对值编码器' },
    //     2: { text: '增量编码器' },
    //   },
    //   width: 60,
    // },
    // {
    //   title: '抱闸',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'brake',
    //   valueType: 'select',
    //   valueEnum: {
    //     0: { text: '不带抱闸' },
    //     1: { text: '带抱闸' },
    //   },
    //   width: 60,
    // },
    // {
    //   title: '额定电压',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'ratedVoltage',
    //   width: 60,
    // },
    // {
    //   title: '额定电流',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'ratedCurrent',
    //   width: 60,
    // },
    // {
    //   title: '额定功率',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'ratedPower',
    //   width: 60,
    // },
    // {
    //   title: '额定速度',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'ratedSpeed',
    //   width: 60,
    // },
    // {
    //   title: '额定转矩',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'ratedTorque',
    //   width: 60,
    // },
    // {
    //   title: '电机惯量',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'motorInertia',
    //   width: 60,
    // },
    // {
    //   title: 't [ms]',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'motorTime',
    //   width: 60,
    // },
    // {
    //   title: '额定速度 [1/s]',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'ratedSecSpeed',
    //   width: 60,
    // },
    // {
    //   title: 'ω [rad/s]',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'angularVel',
    //   width: 60,
    // },
    // {
    //   title: '角加速度a',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'angularAcc',
    //   width: 60,
    // },
    // {
    //   title: '加速力矩Macc',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'accMoment',
    //   width: 60,
    // },
    // {
    //   title: 'Macc/Me [%]',
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'momentRatio',
    //   width: 60,
    // },
    {
      title: '速度环增益默认Kp',
      search: false,
      align: 'center',
      dataIndex: 'kpDefault',
      width: 80,
    },
    {
      title: '速度环积分默认Tn',
      search: false,
      align: 'center',
      dataIndex: 'tnDefault',
      width: 80,
    },
    {
      title: '位置环增益默认',
      search: false,
      align: 'center',
      dataIndex: 'kprDefault',
      width: 80,
    },
    {
      title: '位置环滤波默认',
      search: false,
      align: 'center',
      dataIndex: 'posFilterDefault',
      width: 80,
    },
    {
      title: '负载类型',
      align: 'center',
      dataIndex: 'loadType',
      valueType: 'select',
      valueEnum: {
        1: { text: '水平' },
        2: { text: '旋转' },
        3: { text: '垂直' },
        4: { text: '斜坡' },
        5: { text: '其它' },
      },
      width: 60,
    },
    {
      title: '机械结构',
      search: false,
      align: 'center',
      dataIndex: 'mechanicalStructure',
      valueType: 'select',
      valueEnum: {
        1: { text: '丝杠' },
        2: { text: '齿轮齿条' },
        3: { text: '皮带轮' },
        4: { text: '圆盘' },
        5: { text: '辊式带' },
        6: { text: '链条' },
        7: { text: '其它' },
      },
      width: 60,
    },
    {
      title: '通讯报文',
      search: false,
      align: 'center',
      dataIndex: 'commTelegram',
      valueType: 'select',
      valueEnum: {
        105: { text: '105' },
        111: { text: '111' },
        102: { text: '102' },
        3: { text: '3' },
        1: { text: '1' },
      },
      width: 60,
    },
    {
      title: '附加报文',
      search: false,
      align: 'center',
      dataIndex: 'additionalTelegram',
      valueType: 'select',
      valueEnum: {
        999: { text: 'None' },
        750: { text: '750' },
      },
      width: 60,
    },
    {
      title: '控制模式',
      search: false,
      align: 'center',
      dataIndex: 'controlMode',
      valueType: 'select',
      valueEnum: (row) => {
        return {
          1: { text: 'TO' },
          2: { text: 'Epos' },
          3: { text: 'Speed' },
        };
      },
      width: 60,
    },
    {
      title: '电机最大转速',
      search: false,
      align: 'center',
      dataIndex: 'velocityMax',
      width: 70,
    },
    {
      title: '负载转速 (EPOS) (rpm)',
      search: false,
      align: 'center',
      dataIndex: 'gearRationLoad',
      width: 60,
    },
    {
      title: '电机转速 (EPOS) (rpm)',
      search: false,
      align: 'center',
      dataIndex: 'gearRationMotor',
      width: 60,
    },
    {
      title: '10mm对应的LU (EPOS)',
      search: false,
      align: 'center',
      dataIndex: 'positionAccuracy',
      width: 100,
    },
    {
      title: '每转LU (EPOS)',
      search: false,
      align: 'center',
      dataIndex: 'luLoopEpos',
      width: 60,
    },
    {
      title: '位置环增益 (EPOS)',
      search: false,
      align: 'center',
      dataIndex: 'kprEpos',
      width: 80,
    },
    {
      title: '位置环滤波 (EPOS)',
      search: false,
      align: 'center',
      dataIndex: 'posFilterEpos',
      width: 80,
    },
    {
      title: '速度前馈系数 (EPOS)',
      search: false,
      align: 'center',
      dataIndex: 'coeffVelEpos',
      width: 60,
    },
    {
      title: 'EPOS 最大速度',
      search: false,
      align: 'center',
      dataIndex: 'vmaxEpos',
      width: 60,
    },
    {
      title: 'EPOS 最大加速度',
      search: false,
      align: 'center',
      dataIndex: 'accmaxEpos',
      width: 80,
    },
    {
      title: 'EPOS 最大减速度',
      search: false,
      align: 'center',
      dataIndex: 'dccmaxEpos',
      width: 60,
    },
    {
      title: 'EPOS 急动限制',
      search: false,
      align: 'center',
      dataIndex: 'jerkEpos',
      width: 60,
    },
    {
      title: 'EPOS 急动限制激活',
      search: false,
      align: 'center',
      dataIndex: 'jerkActiveEpos',
      width: 60,
    },
    {
      title: '速度环增益Kp (Speed)',
      search: false,
      align: 'center',
      dataIndex: 'kpSpeed',
      width: 70,
    },
    {
      title: '速度环积分时间Tn (Speed)',
      search: false,
      align: 'center',
      dataIndex: 'tnSpeed',
      width: 70,
    },
    {
      title: '斜坡上升时间 (Speed)',
      search: false,
      align: 'center',
      dataIndex: 'tincSpeed',
      width: 70,
    },
    {
      title: '斜坡下降时间 (Speed)',
      search: false,
      align: 'center',
      dataIndex: 'tdecSpeed',
      width: 70,
    },
    {
      title: '斜坡圆弧起始时间 (Speed)',
      search: false,
      align: 'center',
      dataIndex: 'tstartSpeed',
      width: 70,
    },
    {
      title: '斜坡圆弧结束时间 (Speed)',
      search: false,
      align: 'center',
      dataIndex: 'tstopSpeed',
      width: 70,
    },
  ];

  const treeData: DataNode[] = [
    {
      title: '轴名称',
      key: 'lib0',
    },
    {
      title: '默认参数',
      key: 'lib3',
      children: [
        {
          title: '速度环增益默认Kp P29120',
          key: 'lib3-0',
        },
        {
          title: '速度环积分默认Tn P29121',
          key: 'lib3-1',
        },
        {
          title: '位置环增益默认 P29110',
          key: 'lib3-2',
        },
        {
          title: '位置环滤波默认 P2533',
          key: 'lib3-3',
        },
      ],
    },
    {
      title: '驱动配置',
      key: 'lib4',
      children: [
        {
          title: '负载类型',
          key: 'lib4-0',
        },
        {
          title: '机械结构',
          key: 'lib4-1',
        },
        {
          title: '控制报文 P922',
          key: 'lib4-2',
        },
        {
          title: '附加报文 P8864',
          key: 'lib4-3',
        },
        {
          title: '控制模式',
          key: 'lib4-4',
        },
        {
          title: '电机最大转速 P1082',
          key: 'lib4-5',
        },
      ],
    },
    {
      title: '工艺参数',
      key: 'lib5',
      children: [
        {
          title: 'EPOS',
          key: 'lib5-0',
          children: [
            {
              title: '负载转速 P29248',
              key: 'lib5-0-0',
            },
            {
              title: '电机转速 P29249',
              key: 'lib5-0-1',
            },
            {
              title: '10mm对应的LU',
              key: 'lib5-0-2',
            },
            {
              title: '每转LU P29247',
              key: 'lib5-0-3',
            },
            {
              title: '位置环增益 P29110',
              key: 'lib5-0-4',
            },
            {
              title: '位置环滤波 P2533',
              key: 'lib5-0-5',
            },
            {
              title: '速度前馈系数 P29111',
              key: 'lib5-0-6',
            },
            {
              title: 'EPOS 最大速度 P2571',
              key: 'lib5-0-7',
            },
            {
              title: 'EPOS 最大加速度 P2572',
              key: 'lib5-0-8',
            },
            {
              title: 'EPOS 最大减速度 P2573',
              key: 'lib5-0-9',
            },
            {
              title: 'EPOS 急动限制 P2574',
              key: 'lib5-0-10',
            },
            {
              title: 'EPOS 急动限制激活 P2575',
              key: 'lib5-0-11',
            },
          ],
        },
        {
          title: 'Speed',
          key: 'lib5-1',
          children: [
            {
              title: '速度环增益Kp V90 P29120 /S210 P1460',
              key: 'lib5-1-0',
            },
            {
              title: '速度环积分时间Tn V90 P29121 / S210 P1462',
              key: 'lib5-1-2',
            },
            {
              title: '斜坡上升时间 P1120',
              key: 'lib5-1-3',
            },
            {
              title: '斜坡下降时间 P1121',
              key: 'lib5-1-4',
            },
            {
              title: '斜坡圆弧起始时间 P1130',
              key: 'lib5-1-5',
            },
            {
              title: '斜坡圆弧结束时间 P1131',
              key: 'lib5-1-6',
            },
          ],
        },
      ],
    },
  ];

  const onExpand = (expandedKeysValue: React.Key[]) => {
    console.log('onExpand', expandedKeysValue);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue: React.Key[]) => {
    console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
  };

  const onFinish = async (values: Record<string, any>) => {
    try {
      const result = driveRef.current.getFieldsValue();
      console.log(result, '---result2---');
      if (axiosCreate) {
        result.id = (Math.random() * 1000000).toFixed(0);
        setDataSource([...dataSource, result]);
        delete result.vmaxEposTran;
        await addDriveParaLib(result);
        message.success('添加成功');
      } else {
        if (result.id !== null && result.id !== undefined) {
          for (let i = 0; i < dataSource.length; i++) {
            if (dataSource[i].id === result.id) {
              Object.assign(dataSource[i], result);
            }
          }
          setDataSource(dataSource);
          delete result.vmaxEposTran;
          await updateDriveParaLib(result);
          message.success('更新成功');
        }
      }
      actionRef.current.reload();
      setLibCommVis(false);
    } catch {}
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProCard split="vertical">
        <ProCard title="可选显示项" colSpan="20%" style={{ maxWidth: '100%', height: '100%' }}>
          <Tree
            checkable
            onExpand={(expandedKeysValue: React.Key[]) => {
              console.log('onExpand', expandedKeysValue);
              // if not set autoExpandParent to false, if children expanded, parent can not collapse.
              // or, you can remove all expanded children keys.
              setExpandedKeys(expandedKeysValue);
              setAutoExpandParent(false);
            }}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            onCheck={onCheck}
            checkedKeys={checkedKeys}
            treeData={treeData}
          />
        </ProCard>
        <ProCard colSpan="80%" style={{ maxWidth: '100%', height: '100%' }}>
          <ProList<any>
            headerTitle="驱动参数列表"
            search={{}}
            actionRef={actionRef}
            rowKey="id"
            rowSelection={rowSelection}
            expandable={{ expandedRowKeys, onExpandedRowsChange: setExpandedRowKeys }}
            dataSource={dataSource}
            toolBarRender={() => [
              <Button
                key="button"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => {
                  setUploadVis(true);
                }}
              >
                导入
              </Button>,
              <Button
                key="button"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => {
                  setValues({});
                  setLibCommVis(true);
                  setAxiosCreate(true);
                }}
              >
                新建
              </Button>,
            ]}
            metas={{
              title: {
                dataIndex: 'index',
                valueType: 'index',
                search: false,
              },

              subTitle: {
                search: false,
                render: (text, row) => {
                  return (
                    <DriveParaSubtitle row={row} checkedKeys={checkedKeys} />
                  );
                },
              },

              description: {
                dataIndex: 'para',
                search: false,
                render: (_, row) => {
                  return <DriveParaDescription row={row} />;
                },
              },

              content: {
                search: false,
              },
              actions: {
                search: false,
                render: (text, row) => [
                  <a
                    href={row.html_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    key="modify"
                    onClick={async () => {
                      setAxiosCreate(false);
                      setLibCommVis(true);
                      if (row.vmaxEpos == null && row.vmaxEpos == undefined) {
                        setValues({...row});
                      } else if (row.positionAccuracy == null && row.positionAccuracy == undefined) {
                        setValues({...row});
                      } else {
                        setValues({ ...row, vmaxEposTran: 6 * row.vmaxEpos * row.positionAccuracy });
                      } 
                    }}
                  >
                    编辑
                  </a>,
                  <a
                    href={row.html_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    key="copy"
                    onClick={async () => {
                      let addone = {};
                      dataSource
                        .filter((item) => item.id == row.id)
                        .map((item) => {
                          addone = { ...item };
                        });
                      addone.id = (Math.random() * 1000000).toFixed(0);
                      setDataSource([...dataSource, addone]);
                      delete addone.identification;
                      await addDriveParaLib(addone);
                      actionRef.current.reload();
                    }}
                  >
                    复制
                  </a>,
                  <a
                    href={row.html_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    key="delete"
                    onClick={async () => {
                      setDataSource(dataSource.filter((item) => item.id !== row.id));
                      delete row.identification;
                      await delDriveParaLib(row);
                      actionRef.current.reload();
                    }}
                  >
                    删除
                  </a>,
                ],
              },

              motorOrderNum: {
                title: '电机订货号',
              },
            }}
            request={async (params = {}, sort, filter) => {
              console.log(params, sort, filter);
              const result = await getDriveParaLibByPage(params);
              console.log(result, '---result---');
              setDataSource(result.data.content);
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            pagination={{
              showSizeChanger: true,
            }}
          />
          <DriveParaLibCommon
            visible={libCommVis}
            defaultParaVisible={true}
            title="驱动参数库新建"
            disable={false}
            values={values}
            ref={driveRef}
            initialValues={values}
            onCancel={() => {
              setLibCommVis(false);
            }}
            onOk={onFinish}
          />
          <UploadFileSave
            visible={uploadVis}
            tableHeader={columns}
            errorStatus={false}
            ref={uploadRef}
            onOk={async (tables, tableHeader) => {
              console.log(tables, '---tables---');

              console.log(uploadRef.current.fileList, '文件测试---');
              // formData.append('file', uploadRef.current.fileList);
              // console.log(formData, "---formData---");
              // uploadRef.current.fileList.map((file) => {
              //   formData.append('file', file);
              // });
              await uploadDriveParaLibExcel(formData);
              console.log(formData, '---formData---');
              // setDataSource([...dataSource, tables]);
              actionRef.current.reload();
              setUploadVis(false);
            }}
            onChange={(file) => {
              formData.append('file', file);
              console.log(file, '---file---');
            }}
            onCheck={() => {}}
            onCancel={() => {
              setUploadVis(false);
            }}
            title="驱动参数库上传预览"
          />
        </ProCard>
      </ProCard>
    </PageHeaderWrapper>
  );
};

export default DriveParaLib;
